﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
@using Microsoft.AspNetCore.Antiforgery
@inject IAntiforgery Antiforgery
<style>
    .title-with-border {
        border-left: 4px solid #007BFF; /* 蓝色竖线，宽度为4px */
        padding-left: 10px; /* 文字与边框的间距 */
        font-size: 18px; /* 文字大小 */
        font-weight: bold; /* 文字加粗 */
        color: #333; /* 文字颜色 */
    }

    .text-input {
        margin-bottom: 20px; /* 每个文本框下方留出20px的间距 */
        width: 100%;
    }

    .button-container {
        display: flex;
        justify-content: flex-end; /* 内容靠右对齐 */
        gap: 10px; /* 按钮之间的间距（可选） */
        justify-content: center; /* 小屏幕居中对齐 */
    }

    .search-btn {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        color: #1E9FFF;
    }

    .layui-input-inline {
        position: relative;
    }

    .quantity-control {
        display: flex;
        align-items: center;
    }

    .quantity-btn {
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        border: 1px solid #e6e6e6;
        cursor: pointer;
        user-select: none;
    }

    .quantity-input {
        width: 60px !important;
        text-align: center;
        margin: 0 5px;
    }

    /* 自动生成按钮样式 */
    .auto-generate-container {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .auto-generate-btn {
        background: #1E9FFF;
        color: #fff;
        border: none;
        padding: 6px 15px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 12px;
        white-space: nowrap;
        transition: all 0.3s ease;
    }

        .auto-generate-btn:hover {
            background: #0084E8;
        }

        .auto-generate-btn.manual-mode {
            background: #FFB800;
        }

            .auto-generate-btn.manual-mode:hover {
                background: #E6A500;
            }

    .input-with-button {
        display: flex;
        align-items: center;
        gap: 10px;
        width: 100%;
    }

        .input-with-button input {
            flex: 1;
            min-width: 280px; /* 确保输入框最小宽度能显示完整编号 */
        }

    /* 专门为维修单编号和设备编码设置更宽的输入框 */
    .code-input-container {
        width: 350px !important; /* 增加容器宽度 */
    }

        .code-input-container input {
            width: 250px !important; /* 设置输入框固定宽度 */
            min-width: 250px;
        }
</style>
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body>
    <div class="title-with-border">维修单</div>
    <form class="layui-form" action="">
        @Html.AntiForgeryToken()
        <!-- 隐藏的ID字段，用于更新操作 -->
        <input type="hidden" id="repairId" name="repairId" value="0">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red;">*</span>维修单编号</label>
            <div class="layui-input-inline layui-input-wrap code-input-container">
                <div class="input-with-button">
                    <input type="text" id="workOrder" name="productionWorkOrderCode" lay-verify="required" placeholder="请输入维修单编号" autocomplete="off" readonly class="layui-input">
                    <button type="button" class="auto-generate-btn" onclick="toggleAutoGenerate('workOrder', this)">
                        <i class="layui-icon layui-icon-refresh"></i> 自动生成
                    </button>
                </div>
            </div>
            <label class="layui-form-label"><span style="color: red;">*</span>维修单名称</label>
            <div class="layui-input-inline layui-input-wrap">
                <input type="text" id="productionTask" name="productionTask" lay-verify="required" placeholder="请输入维修单名称" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label"><span style="color: red;">*</span>设备编码</label>
            <div class="layui-input-inline layui-input-wrap code-input-container">
                <div class="input-with-button">
                    <input type="text" id="reporter" name="reporter" lay-verify="required" placeholder="请输入设备编码" autocomplete="off" readonly class="layui-input">
                    <button type="button" class="auto-generate-btn" onclick="toggleAutoGenerate('reporter', this)">
                        <i class="layui-icon layui-icon-refresh"></i> 自动生成
                    </button>
                </div>
            </div>
            <label class="layui-form-label"><span style="color: red;">*</span>设备名称</label>
            <div class="layui-input-inline layui-input-wrap">
                <input type="text" id="reviewer" name="approver" lay-verify="required" placeholder="请输入设备名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red;">*</span>保修日期</label>
            <div class="layui-input-inline layui-input-wrap">
                <input type="date" id="productCode" name="productMaterialCode" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label"><span style="color: red;">*</span>维修完成日期</label>
            <div class="layui-input-inline layui-input-wrap">
                <input type="date" id="productName" name="productMaterialName" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label"><span style="color: red;">*</span>验收日期</label>
            <div class="layui-input-inline layui-input-wrap">
                <input type="date" id="unit" name="unit" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">单据状态:</label>
            <div class="layui-input-inline">
                <select name="states" id="states" lay-verify="required">
                    <option value="">请选择状态</option>
                    <option value="1">草稿</option>
                    <option value="2">已确认</option>
                    <option value="3">审核中</option>
                    <option value="4">已审批</option>
                    <option value="5">已完成</option>
                    <option value="6">已拒绝</option>
                </select>
            </div>
            <label class="layui-form-label">维修结果:</label>
            <div class="layui-input-inline">
                <select name="states" id="repairResults" lay-verify="required">
                    <option value="">请选择状态</option>
                    <option value="已完成">已完成</option>
                    <option value="未完成">未完成</option>
                </select>
            </div>
            <label class="layui-form-label"><span style="color: red;">*</span>维修人员</label>
            <div class="layui-input-inline">
                <select name="repairPersonnel" id="repairPersonnel" lay-verify="required">
                    <option value="">请选择维修人员</option>
                    <option value="张维修员">张维修员</option>
                    <option value="李维修员">李维修员</option>
                    <option value="赵维修员">赵维修员</option>
                    <option value="王维修员">王维修员</option>
                </select>
            </div>
            <label class="layui-form-label"><span style="color: red;">*</span>验收人员</label>
            <div class="layui-input-inline">
                <select name="acceptancePersonnel" id="acceptancePersonnel" lay-verify="required">
                    <option value="">请选择验收人员</option>
                    <option value="张验收人员">张验收人员</option>
                    <option value="李验收人员">李验收人员</option>
                    <option value="赵验收人员">赵验收人员</option>
                    <option value="王验收人员">王验收人员</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item form-actions button-container">
            <div class="layui-input-block">
                <button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="userForm">
                    <i class="layui-icon layui-icon-ok"></i> 更新
                </button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="returnquery()">
                    <i class="layui-icon layui-icon-return"></i> 返回
                </button>
            </div>
        </div>
    </form>
</body>
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    layui.use(['form', 'layer'], function() {
        var form = layui.form;
        var layer = layui.layer;

        // 页面加载时获取URL参数中的ID并加载数据
        var urlParams = new URLSearchParams(window.location.search);
        var repairId = urlParams.get('id');
        
        if (repairId && repairId > 0) {
            $('#repairId').val(repairId);
            loadRepairData(repairId);
        } else {
            layer.msg('缺少维修单ID参数', { icon: 2 });
            setTimeout(function() {
                window.history.back();
            }, 2000);
        }

        // 监听表单提交
        form.on('submit(userForm)', function(data) {
            // 构建提交数据，匹配 RepairDto 结构
            var formData = {
                Id: parseInt($('#repairId').val()) || 0, // 添加ID字段
                RepairCode: $('#workOrder').val(),
                RepairName: $('#productionTask').val(),
                DeviceCode: $('#reporter').val(),
                DeviceName: $('#reviewer').val(),
                WarrantyDate: $('#productCode').val(),  // 修正拼写：WarrantyDate
                RepairDate: $('#productName').val(),
                AcceptanceDate: $('#unit').val(),
                RepairResults: $('#repairResults').val(), // 维修结果
                RepairPersonnel: $('select[name="repairPersonnel"]').val(),
                AcceptancePersonnel: $('select[name="acceptancePersonnel"]').val(),
                DocumentStatus: parseInt($('#states').val()) || 0
            };

            // 表单验证
            if (!formData.RepairCode) {
                layer.msg('请输入维修单编号', {icon: 2});
                return false;
            }
            if (!formData.RepairName) {
                layer.msg('请输入维修单名称', {icon: 2});
                return false;
            }
            if (!formData.DeviceCode) {
                layer.msg('请输入设备编码', {icon: 2});
                return false;
            }
            if (!formData.DeviceName) {
                layer.msg('请输入设备名称', {icon: 2});
                return false;
            }
            if (!formData.WarrantyDate) {
                layer.msg('请选择保修日期', {icon: 2});
                return false;
            }
            if (!formData.RepairDate) {
                layer.msg('请选择维修完成日期', {icon: 2});
                return false;
            }
            if (!formData.AcceptanceDate) {
                layer.msg('请选择验收日期', {icon: 2});
                return false;
            }
            if (!formData.RepairPersonnel) {
                layer.msg('请选择维修人员', {icon: 2});
                return false;
            }
            if (!formData.AcceptancePersonnel) {
                layer.msg('请选择验收人员', {icon: 2});
                return false;
            }
            if (!formData.DocumentStatus) {
                layer.msg('请选择单据状态', {icon: 2});
                return false;
            }

            // 显示加载层
            var loadingIndex = layer.load(1, {
                shade: [0.1, '#fff']
            });

            // 添加防伪令牌到表单数据
            formData['__RequestVerificationToken'] = $('input[name="__RequestVerificationToken"]').val();

            // 调试：打印表单数据
            console.log('提交的表单数据:', formData);

            // 提交数据到后端
            $.ajax({
                url: '/RepairOrders/UpdateRepair',
                type: 'POST',
                data: formData,
                success: function(response) {
                    layer.close(loadingIndex);
                    // UpdateRepair 返回的是 int 类型，大于0表示成功
                    if (response > 0) {
                        layer.msg('更新成功！', {
                            icon: 1,
                            time: 1500
                        }, function() {
                            // 跳转到 ShowRepair 页面并刷新
                            window.location.href = '/RepairOrders/ShowRepair';
                        });
                    } else {
                        layer.msg('更新失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    layer.close(loadingIndex);
                    console.error('提交失败:', error);
                    console.error('响应状态:', xhr.status);
                    console.error('响应内容:', xhr.responseText);

                    var errorMsg = '网络错误，请稍后重试';
                    try {
                        var response = JSON.parse(xhr.responseText);
                        if (response && response.message) {
                            errorMsg = response.message;
                        }
                    } catch (e) {
                        // 如果不是JSON格式，直接显示响应文本
                        if (xhr.responseText) {
                            errorMsg = xhr.responseText.length > 100 ?
                                xhr.responseText.substring(0, 100) + '...' :
                                xhr.responseText;
                        }
                    }

                    layer.msg(errorMsg, {icon: 2});
                }
            });

            return false; // 阻止表单默认提交
        });
    });

    // 加载维修单数据并反填到表单
    function loadRepairData(id) {
        // 显示加载层
        var loadingIndex = layer.load(1, {
            shade: [0.1, '#fff']
        });

        $.ajax({
            url: '/RepairOrders/FindRepair',
            type: 'GET',
            data: { id: id },
            success: function(response) {
                layer.close(loadingIndex);
                
                if (response && response.length > 0) {
                    var data = response[0]; // FindRepair返回的是数组，取第一个元素
                    
                    // 反填基本信息
                    $('#workOrder').val(data.repairCode || '');
                    $('#productionTask').val(data.repairName || '');
                    $('#reporter').val(data.deviceCode || '');
                    $('#reviewer').val(data.deviceName || '');
                    
                    // 反填日期信息（转换为input date格式）
                    $('#productCode').val(formatDateForInput(data.warrantyDate));
                    $('#productName').val(formatDateForInput(data.repairDate));
                    $('#unit').val(formatDateForInput(data.acceptanceDate));
                    
                    // 反填选择框信息
                    $('#states').val(data.documentStatus || '');
                    $('#repairResults').val(data.repairResults || '');
                    $('#repairPersonnel').val(data.repairPersonnel || '');
                    $('#acceptancePersonnel').val(data.acceptancePersonnel || '');
                    
                    // 当是编辑模式时，允许手动输入编号
                    var workOrderBtn = document.querySelector('[onclick*="workOrder"]');
                    var reporterBtn = document.querySelector('[onclick*="reporter"]');
                    
                    if (workOrderBtn) {
                        workOrderBtn.classList.add('manual-mode');
                        workOrderBtn.innerHTML = '<i class="layui-icon layui-icon-edit"></i> 手动输入';
                        document.getElementById('workOrder').readOnly = false;
                        document.getElementById('workOrder').style.backgroundColor = '#fff';
                    }
                    
                    if (reporterBtn) {
                        reporterBtn.classList.add('manual-mode');
                        reporterBtn.innerHTML = '<i class="layui-icon layui-icon-edit"></i> 手动输入';
                        document.getElementById('reporter').readOnly = false;
                        document.getElementById('reporter').style.backgroundColor = '#fff';
                    }
                    
                    // 重新渲染表单元素
                    layui.form.render();
                } else {
                    layer.msg('未找到维修单数据', { icon: 2 });
                    setTimeout(function() {
                        window.history.back();
                    }, 2000);
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadingIndex);
                console.error('加载数据失败:', error);
                console.error('响应状态:', xhr.status);
                console.error('响应内容:', xhr.responseText);
                
                var errorMsg = '加载数据失败';
                if (xhr.status === 404) {
                    errorMsg = '维修单不存在';
                } else if (xhr.status === 500) {
                    errorMsg = '服务器内部错误';
                } else if (error) {
                    errorMsg = '加载数据失败: ' + error;
                }
                
                layer.msg(errorMsg, { icon: 2 });
                setTimeout(function() {
                    window.history.back();
                }, 3000);
            }
        });
    }

    // 格式化日期为input date控件需要的格式 (YYYY-MM-DD)
    function formatDateForInput(dateString) {
        if (!dateString) return '';
        
        var date = new Date(dateString);
        if (isNaN(date.getTime())) return '';
        
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
    }

    // 切换自动生成和手动输入模式
    function toggleAutoGenerate(inputId, button) {
        const input = document.getElementById(inputId);
        const isAutoMode = button.classList.contains('manual-mode');

        if (isAutoMode) {
            // 切换到自动生成模式
            button.classList.remove('manual-mode');
            button.innerHTML = '<i class="layui-icon layui-icon-refresh"></i> 自动生成';
            input.readOnly = true;
            input.style.backgroundColor = '#f5f5f5';

            // 自动生成编号
            if (inputId === 'workOrder') {
                input.value = generateRepairOrderCode();
            } else if (inputId === 'reporter') {
                input.value = generateEquipmentCode();
            }
        } else {
            // 切换到手动输入模式
            button.classList.add('manual-mode');
            button.innerHTML = '<i class="layui-icon layui-icon-edit"></i> 手动输入';
            input.readOnly = false;
            input.style.backgroundColor = '#fff';
            input.value = ''; // 清空输入框内容
            input.focus();
        }
    }

    // 生成维修单编号
    function generateRepairOrderCode() {
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const time = String(date.getHours()).padStart(2, '0') + String(date.getMinutes()).padStart(2, '0') + String(date.getSeconds()).padStart(2, '0');
        const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0');
        const timestamp = String(Date.now()).slice(-3); // 取时间戳后3位确保唯一性
        return `WX${year}${month}${day}${time}${random}${timestamp}`;
    }

    // 生成设备编码
    function generateEquipmentCode() {
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const time = String(date.getHours()).padStart(2, '0') + String(date.getMinutes()).padStart(2, '0');
        const random = String(Math.floor(Math.random() * 10000)).padStart(4, '0');
        const timestamp = String(Date.now()).slice(-2); // 取时间戳后2位确保唯一性
        return `EQ${year}${month}${day}${time}${random}${timestamp}`;
    }

    // 初始化页面时自动生成编号
    document.addEventListener('DOMContentLoaded', function() {
        // 为维修单编号和设备编码初始生成编号
        document.getElementById('workOrder').value = generateRepairOrderCode();
        document.getElementById('reporter').value = generateEquipmentCode();
    });

    function returnquery() {
        // 返回查询页面的逻辑
        window.history.back();
    }
</script>
